package com.example.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.example.common.constants.BehaviorConstants;
import com.example.common.redis.CacheService;
import com.example.common.util.R;
import com.example.common.util.ResultCodeRecord;
import com.example.model.article.dto.CollectionBehaviorDto;
import com.example.model.user.pojo.User;
import com.example.utils.thread.UserThreadLocal;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.article.service.CollectionService;
import com.example.model.article.pojo.Collections;
import com.example.article.mapper.CollectionMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

@Service
@Slf4j
public class CollectionServiceImpl extends ServiceImpl< CollectionMapper, Collections > implements CollectionService {
    @Autowired
    private CacheService cacheService;

    @Override
    public boolean collection(CollectionBehaviorDto collectionBehaviorDto) {
        // 1、条件判断
        if (collectionBehaviorDto == null || collectionBehaviorDto.getEntryId() == null) {
            return R.error(ResultCodeRecord.PARAM_INVALID).isFlag();
        }

        // 2、判断是否登录
        User user = UserThreadLocal.getUser();
        if (user == null) {
            return R.error(ResultCodeRecord.NEED_LOGIN).isFlag();
        }

        // 3、查询
        String collectionJson = (String) cacheService.hGet(BehaviorConstants.COLLECTION_BEHAVIOR + user.getUserId(), collectionBehaviorDto.getEntryId().toString());
        if (StringUtils.isNotBlank(collectionJson) && collectionBehaviorDto.getOperation() == 0) {
            return R.error(ResultCodeRecord.PARAM_INVALID, "已收藏").isFlag();
        }
        // 4、收藏
        if (collectionBehaviorDto.getOperation() == 0) {
            log.info("文章收藏，保存key：{}, {}, {}", collectionBehaviorDto.getEntryId(), user.getUserId().toString(), JSON.toJSONString(collectionBehaviorDto));
            cacheService.hPut(BehaviorConstants.COLLECTION_BEHAVIOR + user.getUserId(), collectionBehaviorDto.getEntryId().toString(), JSON.toJSONString(collectionBehaviorDto));
        } else {
            log.info("文章取消收藏，删除key：{}, {}, {}", collectionBehaviorDto.getEntryId(), user.getUserId().toString(), JSON.toJSONString(collectionBehaviorDto));
            cacheService.hDelete(BehaviorConstants.COLLECTION_BEHAVIOR + user.getUserId(), collectionBehaviorDto.getEntryId().toString());
        }
        return true;
    }
}